from rest_framework import serializers

from couple_segment.models import CoupleSegment
from ship_segments.models import ShipSegment

# 序列化 ShipSegment 所有字段
class ShipSegmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = ShipSegment
        exclude = ['ship_number', 'ship_type']  # 排除公共字段，在外层显示

# 主要返回结构
class CoupleSegmentCompareSerializer(serializers.Serializer):
    common = serializers.DictField()
    data1 = ShipSegmentSerializer()
    data2 = ShipSegmentSerializer()


class CoupleSegmentImportSerializer(serializers.Serializer):
    ship_number = serializers.CharField(max_length=50, required=True)
    segment_number = serializers.CharField(max_length=50, required=True)
    combined_segment = serializers.CharField(max_length=50, required=True)

    def validate(self, data):
        if data['segment_number'] == data['combined_segment']:
            raise serializers.ValidationError("分段号和组合分段号不能相同")
        return data

    def create(self, validated_data):
        ship_number = validated_data.get("ship_number")
        segment_number = validated_data.get("segment_number")
        combined_segment = validated_data.get("combined_segment")

        try:
            current_segment = ShipSegment.objects.get(
                ship_number=ship_number,
                segment_number=segment_number
            )
            combined_segment_obj = ShipSegment.objects.get(
                ship_number=ship_number,
                segment_number=combined_segment
            )

            # 构造主键
            current_id = current_segment.ship_segments_id
            combined_id = combined_segment_obj.ship_segments_id

            # 检查是否已存在
            exists = CoupleSegment.objects.filter(
                ship_segments_id=current_id,
                combined_segment_id=combined_id
            ).exists()

            if exists:
                # 如果已存在，不插入也不报错
                return None

            # 创建新记录
            return CoupleSegment.objects.create(
                ship_segments_id=current_id,
                combined_segment_id=combined_id
            )

        except ShipSegment.DoesNotExist as e:
            raise serializers.ValidationError(f"找不到对应的 ShipSegment: {str(e)}")